/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageData;
import io.renren.common.validator.Assert;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import io.renren.modules.carinfo.entity.CarInfoEntity;
import io.renren.modules.carinfo.vo.CarInfoVO;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public UserEntity queryByMobile(String mobile) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", mobile));
	}

	@Override
	public long login(LoginForm form) {
		UserEntity user = queryByMobile(form.getUsername());
		Assert.isNull(user, "账号错误");

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
			throw new RRException("密码错误");
		}

		return user.getUserId();
	}

    @Override
    public UserEntity queryByUserId(Long userId) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
		return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
		UserEntity userEntity = new UserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<UserEntity>().eq("user_id", userId).eq("password", password));
    }

    @Override
    public PageData<UserEntity> userinfolist(Map<String, Object> params) {
		// 获取信息
		String customerName = (String) params.get("customerName");
		Integer page = Integer.valueOf((String) params.get("page"));
		Integer limit = Integer.valueOf((String) params.get("limit"));
		QueryWrapper<UserEntity> wrapper = new QueryWrapper<UserEntity>();
		if (StringUtils.isNotBlank(customerName)) {
			wrapper.like("customer_name",customerName);
		}
		// 创建分页对象
		IPage<UserEntity> iPage = new Page<UserEntity>(page,limit);
		this.baseMapper.selectPage(iPage,wrapper);
		// 分页集合
		List<UserEntity> records = iPage.getRecords();
		// 总数
		long total = iPage.getTotal();
		PageData<UserEntity> pageData = new PageData<UserEntity>(records,total);
		return pageData;
    }
}
